package com.ynyr.jar.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class FileUtil {

    private FileUtil() {
    }

    public static String combination(String... paths) {
        StringBuffer sb = new StringBuffer();
        for (String path : paths) {
            if (path == null) {
                break;
            }
            if (path.indexOf(":") < 0) {
                path = path.startsWith(File.separator) ? path : (File.separator + path);
            }
            path = path.endsWith(File.separator) ? path.substring(0, path.length() - 1) : path;
            sb.append(path);
        }
        return sb.toString();
    }

    public static String getMd5(Path path) {
        BigInteger bi = null;
        try {
            byte[] buffer = new byte[8192];
            int len = 0;
            MessageDigest md = MessageDigest.getInstance("MD5");
            File f = path.toFile();
            FileInputStream fis = new FileInputStream(f);
            while ((len = fis.read(buffer)) != -1) {
                md.update(buffer, 0, len);
            }
            fis.close();
            byte[] b = md.digest();
            bi = new BigInteger(1, b);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bi.toString(16);
    }

    public static void removeDir(Path path) {
        File file = path.toFile();

        if(file.isDirectory()) {
            File[] subs = file.listFiles();

            if(ArrayUtils.isEmpty(subs)) {
                return;
            }

            for(int i = 0; i < subs.length; i++) {
                File sub = subs[i];

                if(sub.isDirectory()) {
                    removeDir(sub.toPath());
                } else {
                    deleteSingleFile(sub.toPath());
                }
            }

            deleteSingleFile(file.toPath());
        } else {
            deleteSingleFile(file.toPath());
        }
    }

    private static void deleteSingleFile(Path path) {
        File file = path.toFile();
        String absolutePath = file.getAbsolutePath();
        boolean isOk = file.delete();
        log.info("删除[{}]{}", absolutePath, isOk ? "成功" : "失败");
    }
}
